package com.echat.elocation.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echat.elocation.R;
import com.echat.elocation.base.BaseActivity;
import com.echat.elocation.callback.PermissionListener;
import com.echat.elocation.constant.Constants;
import com.echat.elocation.event.LocationEvent;
import com.echat.elocation.event.NetworkEvent;
import com.echat.elocation.manager.ActivityCollector;
import com.echat.elocation.manager.UserInfoManager;
import com.echat.elocation.service.TerminalService;
import com.echat.elocation.util.DataFormatUtil;
import com.echat.elocation.util.GpsUtils;
import com.echat.elocation.util.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

import static com.echat.elocation.constant.Constants.ACCOUNT_SL_ACCOUNT_READ;

/**
 * @author lihao
 * @date 2018/7/11 9:30
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, PermissionListener {

    private static final String TAG = "MainActivity";

    private RelativeLayout networkBar;
    private SwipeRefreshLayout swipeRefresh;
    private TextView txtLongitude;
    private TextView txtLatitude;
    private TextView txtGpsTime;
    private TextView txtSpeed;
    private TextView txtDirection;
    private TextView txtProvider;

    private static final int SETTING_REQUEST_CODE = 0;
    private static final int GPS_REQUEST_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        EventBus.getDefault().register(this);
        requestPermission(permissions, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopTerminal();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        initMenu();
        networkBar = findViewById(R.id.rl_network);
        swipeRefresh = findViewById(R.id.swipe_refresh);
        txtLongitude = findViewById(R.id.txt_longitude);
        txtLatitude = findViewById(R.id.txt_latitude);
        txtGpsTime = findViewById(R.id.txt_gpstime);
        txtSpeed = findViewById(R.id.txt_speed);
        txtDirection = findViewById(R.id.txt_direction);
        txtProvider = findViewById(R.id.txt_provider);
        networkBar.setOnClickListener(this);
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefresh.setOnRefreshListener(() -> {
            swipeRefresh.setRefreshing(false);
        });
    }

    private void initMenu() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setting:
                openActivity(SettingActivity.class);
                break;
            case R.id.exit:
                stopTerminal();
                ActivityCollector.finishAll();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
            startTerminal();
        }
    }

    @Override
    public void onGranted() {
        startTerminal();
    }

    @Override
    public void onDenied(List<String> deniedPermissions) {
        Logger.w(TAG, "onDenied: " + Arrays.toString(new List[]{deniedPermissions}));
    }

    private boolean checkConfig() {
        return UserInfoManager.isSave(this);
    }

    /**
     * 网络变化时触发
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkChange(NetworkEvent event) {
        if (event.isEnable()) {
            networkBar.setVisibility(View.GONE);
        } else {
            networkBar.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 定位成功是触发，将数据加载显示
     *
     * @param event
     */
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loadLocationData(LocationEvent event) {
        DecimalFormat formatter = new DecimalFormat("0.0000");
        txtLongitude.setText(formatter.format(event.getLongitude()));
        txtLatitude.setText(formatter.format(event.getLatitude()));
        txtGpsTime.setText(DataFormatUtil.getGpsLocalTime(event.getGpsTime()));
        txtSpeed.setText(formatter.format(event.getSpeed() * 3.6f) + "km/h");
        txtDirection.setText(DataFormatUtil.getDirection(event.getBearing()));
        txtProvider.setText(event.getProvider() + "，卫星：" + event.getNumSatellite() + "颗");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_network:
                startActivity(new Intent(Settings.ACTION_SETTINGS));
                break;
            default:
                break;
        }
    }

    private void showOpenSettings() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("未配置用户信息，是否现在设置？");
        builder.setPositiveButton("确认", (dialog, which) -> openActivity(SettingActivity.class));
        builder.setNegativeButton("取消", (dialog, which) -> finish());
        builder.create().show();
    }

    private void showOpenGpsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用需要打开定位功能。\n请点击“设置”-“定位服务”-打开定位功能");
        builder.setPositiveButton("设置", (dialog, which) -> GpsUtils.openGps(MainActivity.this, GPS_REQUEST_CODE));
        builder.setNegativeButton("取消", (dialog, which) -> finish());
    }

    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。\n请点击“设置”-“权限”-打开所需权限");
        builder.setPositiveButton("设置", (dialog, which) -> startSystemSetting());
        builder.setNegativeButton("取消", (dialog, which) -> finish());
    }

    /**
     * 开启后端定位服务
     */
    private void startTerminal() {
        if (GpsUtils.isOpenGps()) {
            if (!checkConfig()) {
                if (Constants.userSlAccount(Build.MODEL)) {
                    Log.i(TAG, "onGranted: 发送善里广播");
                    sendBroadcast(new Intent(ACCOUNT_SL_ACCOUNT_READ));
                } else {
                    showOpenSettings();
                }
            } else {
                Intent intent = new Intent(this, TerminalService.class);
                startService(intent);
            }

        } else {
            GpsUtils.openGps(MainActivity.this, GPS_REQUEST_CODE);
        }
    }

    private void stopTerminal() {
        Intent intent = new Intent(this, TerminalService.class);
        stopService(intent);
    }

    private void startSystemSetting() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, SETTING_REQUEST_CODE);
    }

}
